<!-- 事例 -->
<template>
  <div class="dialogdiv">
    <el-dialog :modal-append-to-body='false' :title="title" v-loading="loading" element-loading-text="加载中..."
      element-loading-background="rgba(0, 0, 0, 0.5)" :visible.sync="showModal" width="600px"
      :before-close="handleClose">
      <el-form :model="ruleForm" ref="ruleForm" label-position="left" size="mini" :show-message="false">
        <el-form-item label="文件路径" prop="ParentId" :label-width="formLabelWidth">
          <wlTreeSelect class="u-full" nodeKey="id" placeholder="请选择文件路径" :props="tree_select_prop"
            :data="tree_folder_list" v-model="ruleForm.ParentId"></wlTreeSelect>
        </el-form-item>
        <el-form-item v-if="['edit', 'add'].includes(type)" label="文件夹名称" prop="file_name" :label-width="formLabelWidth"
          required>
          <el-input class="elinput" size="small" v-model="ruleForm.file_name" placeholder="文件夹名称" clearable>
          </el-input>
        </el-form-item>
        <el-form-item v-if="['edit', 'add'].includes(type)" label="备注说明" prop="remark" :label-width="formLabelWidth">
          <el-input class="elinput" size="small" v-model="ruleForm.remark" clearable>
          </el-input>
        </el-form-item>
        <el-form-item v-if="type=='addfile'" label="导入文件" prop="fileList" :label-width="formLabelWidth">
          <el-upload class="upload-demo" ref="upload" drag multiple with-credentials action="111"
            :file-list="ruleForm.fileList" :auto-upload="false" :on-change="
                    (file, filesList) =>
                      filehandleChange(file, filesList)
                  " :on-remove="
                    (file, filesList) =>
                    filehandleChange(file, filesList)
                  ">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="modalClose_btn('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitdataModal('ruleForm')">录入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
  import {
    arrayToTree,
    downLoad
  } from "../util/myutil.js";
  export default {
    components: {},
    data() {
      return {
        loading: false,
        title: '',
        type: '', //弹窗类型
        formLabelWidth: "120px",
        ruleForm: {
          remark: '',
          file_name: '',
          ParentId: '',
        },
        tree_folder_list: [],
        tree_select_prop: {
          label: "file_name",
          children: "children",
          value: "id"
        }

      };
    },
    watch: {},
    computed: {
      //是否显示弹框
      showModal() {
        return this.$store.state.showModal
      },
      //显示弹框类型
      modalStatus() {
        return this.$store.state.modalStatus
      }

    },
    props: {
      flagindex: {
        type: Number,
        default: 1
      }
    },
    created() {},
    mounted() {},

    methods: {

      //关闭弹窗
      handleClose() {
        this.$store.commit('showModal', false);
        this.$store.commit('updateModalStatus', '')
      },

      //打开弹窗执行函数
      openFunction(type, file_checked_data) {
        //console.log(type, file_checked_data)
        this.type = type
        switch (type) {
          case "add":
            this.title = '新增文件夹'
            break;
          case "addfile":
            this.title = '上传文件'
            break;
          case "edit":
            this.title = '编辑文件'
            let row = this.$parent.file_checked_data[0]
            this.ruleForm.ParentId = row.pid
            this.ruleForm.file_name = row.file_name
            this.ruleForm.describe = row.describe
            break;
          case "moving":
            this.title = '移动'
            break;
          default:
            break;
        }
        this.getAllFolders()
      },

      filehandleChange(file, filesList) {
        this.ruleForm.fileList = filesList
      },

      //获取所有的文件夹,编辑和筛选的时候
      getAllFolders() {
        this.loading = true;
        let params = {};
        params.is_folder = 1 //获取所有文件夹
        if (['edit', 'moving'].includes(this.type)) {
          // console.log(this.$parent.file_checked_data[0].id)
          params.nopid = this.$parent.file_checked_data[0].id
          //params.noid = this.$parent.file_checked_data
          params.noids = this.commonV.deveridarrry(
            this.$parent.file_checked_data
          )
        }
        let allparams = {
          params: params,
          api: 'fileMangement',
        }
        this.$store
          .dispatch("getmsgData", allparams)
          .then(response => {
            this.loading = false;
            let res = response.data;
            //console.log(res)
            let _list = res
            this.tree_folder_list = arrayToTree(_list);
            this.ruleForm.ParentId = this.$parent.file.pid
          })
          .catch(err => {
            this.loading = false;
            console.log(err);
            this.$message.error("网络连接错误" + "fileMangement");
          });
      },
      //提交表单内容
      submitdataModal(formName) {
        //console.log(formName)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true;
            let allparams = {}
            let pid = ""
            let return_pid = this.$parent.file.pid
            if (typeof (this.ruleForm.ParentId) == "number") {
              pid = this.ruleForm.ParentId
            } else if (this.ruleForm.ParentId.length != 0) {
              pid = this.ruleForm.ParentId[0].id
            }
            if (['edit', 'add'].includes(this.type)) {
              // 新增文件夹,编辑文件夹
              let params = {}
              let method = ""
              if (this.type == 'add') {
                method = "post"
                params.create_by = JSON.parse(
                  localStorage.getItem("UserMsg")
                ).real_name;
                params.is_folder = 1
              } else {
                method = "put"
                params.edit_by = JSON.parse(
                  localStorage.getItem("UserMsg")
                ).real_name;
                params.id = this.$parent.file_checked_data[0].id
              }
              params.pid = pid
              params.file_name = this.ruleForm.file_name
              params.describe = this.ruleForm.describe
              allparams = {
                params: params,
                api: 'fileMangement',
                method: method,
              }
            } else if (this.type == 'addfile') {
              // '上传文件'
              const params = new FormData();
              let params2 = {}
              /*附件*/
              let exisfile = [];
              for (let index = 0; index < this.ruleForm.fileList.length; index++) {
                let ele = this.ruleForm.fileList[index]
                let elenew = {}
                if (typeof ele.raw != "undefined") {
                  elenew.is_folder = 0
                  elenew.suffix_name = this.getType(ele.name)
                  elenew.file_name = ele.name
                  elenew.file_size = ele.size
                  // elenew.file_path = ele.raw
                  elenew.pid = pid
                  elenew.create_by = JSON.parse(localStorage.getItem("UserMsg")).real_name
                  exisfile.push(elenew);
                }
              }
              params.append("exisfile", JSON.stringify(exisfile))
              for (let index = 0; index < this.ruleForm.fileList.length; index++) {
                params.append("file_path", this.ruleForm.fileList[index].raw)
                // console.log(this.ruleForm.fileList[index])
              }
              allparams = {
                params: params,
                api: 'addfileArr',
                method: "post",
              }
            } else if (this.type == 'moving') {
              // 移动文件夹/文件
              let params = {}
              params.pid = pid
              let gfdsg = []
              let file_checked_data = this.$parent.file_checked_data
              params.ids = this.commonV.deveridarrry(file_checked_data);
              allparams = {
                params: params,
                api: 'movefileArr',
                method: "post",
              }
              // return_pid = pid
            }
            this.$store
              .dispatch("editmsgData", allparams)
              .then(response => {
                this.loading = false;
                let res = response.data;
                //  console.log(res)
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.handleClose()
                //不记录访问路径
                this.$parent.refreshFileList([return_pid, pid], this.type)
              })
              .catch(err => {
                this.loading = false;
                console.log(err);
                this.$message.error("网络连接错误" + "fileMangement");
              });

          } else {
            return false;
          }
        })
      },
      //获取文件后缀
      getType(file) {
        let filename = file;
        let index1 = filename.lastIndexOf(".");
        let index2 = filename.length;
        //alert(index2);
        let type = filename.substring(index1 + 1, index2);
        return type;
      },


    }
  };

</script>
<style scoped>
  .dialogdiv>>>.u-full {
    width: 100%;
  }

</style>
